﻿using System.Configuration;

namespace JPR.Common.Configuration
{
	public static class AppSettings
	{
		#region Public properties

		public static string GetStringValueByKey(string key)
		{
			return GetString(key);
		}

		public static int GetIntValueByKey(string key)
		{
			return GetInt(key);
		}

		public static int ListenerPort
		{
			get { return GetInt("ListenerPort"); }
		}

		public static string RemoteAddress
		{
			get { return GetStringOrDefault("RemoteAddress", "localhost"); }
		}

		public static int RemotePort
		{
			get { return GetIntOrDefault("RemotePort", 1234); }
		}

		public static string RemoteObject
		{
			get { return GetStringOrDefault("RemoteObject", "News.rss"); }
		}

		public static byte[] CryptoIV
		{
			get { return GetBytes("IVKey"); }
		}

		public static byte[] CryptoKey
		{
			get { return GetBytes("CryptoKey"); }
		}

		public static int MaxNumberOfConnection
		{
			get { return GetIntOrDefault("MaxNumberOfConnection", 10); }
		}

		#endregion

		#region Common methods

		private static string GetAppSettingValueOrDefault(string key)
		{
			return GetAppSettingValueOrDefault(key, string.Empty);
		}

		private static string GetAppSettingValueOrDefault(string key, string defaultValue)
		{
			string appSettingValue = ConfigurationManager.AppSettings[key];
			if(string.IsNullOrEmpty(appSettingValue))
			{
				return defaultValue;
			}
			return appSettingValue;
		}

		private static int GetInt(string key)
		{
			return GetIntOrDefault(key, 0);
		}

		private static int GetIntOrDefault(string key, int defaultValue)
		{
			int ret;
			if (int.TryParse(GetAppSettingValueOrDefault(key), out ret))
			{
				return ret;
			}
			return defaultValue;
		}

		private static string GetString(string key)
		{
			return GetStringOrDefault(key, string.Empty);
		}

		private static string GetStringOrDefault(string key, string defaultValue)
		{
			return GetAppSettingValueOrDefault(key, defaultValue);
		}

		private static byte[] GetBytes(string key)
		{
			return System.Text.Encoding.ASCII.GetBytes(GetAppSettingValueOrDefault(key));
		}

		#endregion

	}
}